<template>
  <div>

    <div class="card-container" style="display: flex; flex-wrap: wrap; margin-top: 20px;">
      <div v-for="(item, index) in arr" :key="index" class="card-wrapper" style="margin-top: 50px;">
        <el-card class="custom-card" style="max-width: 400px;margin-left: 100px">
          <div class="card-header" style="display: flex; align-items: center;">
            <!-- 图片显示在左边 -->
            <div class="card-image">
              <img :src="item.pic" alt="小区图片" style="width: 100px; height: 100px; margin-right: 20px;">
            </div>
            <!-- 数据显示在右边 -->
            <div class="card-info">
              <h3>{{ item.name }}</h3>
              <p>{{ item.address }}</p> <!-- 假设plotName是小区名称 -->
              <p>辖区：{{ item.divisionName }}</p> <!-- 假设plotName是小区名称 -->
            </div>
          </div>
          <div class="card-body" @click="tenement(item.id)" >
            <!-- 详细信息区域，两个字段一组排列 -->
            <div style="display: flex; flex-wrap: wrap;">
              <div style="flex: 1 1 50%;">
                <p class="text item">实有人口口口: {{ item.populationCount }}</p>
                <p class="text item">实有房屋: {{ item.roomCount }}</p>
                <p class="text item">实有单位: 2</p>
                <!-- 其他单个字段 -->
              </div>
              <div style="flex: 1 1 50%;">
                <p class="text item">实有车辆: {{ item.carCount }}</p>
                <p class="text item">实有力量: 1</p>
                <p class="text item">实有设备: {{ item.equipmentCount }}</p>
                <!-- 其他成对字段 -->
              </div>
              <!-- 如果字段数量不是偶数，可能需要额外的div来容纳剩余的字段 -->
            </div>
          </div>
          <template #footer>
            <div>Footer content</div>
          </template>
        </el-card>
      </div>
    </div>


    <el-form ref="form" :model="plot" label-width="100px" style="margin-top: 20px;margin-left: -45px" >
      <el-form-item>
        <el-button icon="el-icon-plus" size="small" @click="add">新增小区</el-button>
        <el-button style="float: right;margin-right: 30px" icon="el-icon-refresh" @click="cancle" ></el-button>
        <el-button style="float: right;margin-right: 10px" type="primary" icon="el-icon-search" @click="list" ></el-button>
        <el-input  style="width: 250px;float: right;margin-right: 10px" placeholder="请输入小区名称、地址、编号" v-model="plot.name"></el-input>
        <el-select v-model="plot.divisionId" placeholder="请选择行政区域" style="float: right;margin-right: 10px" >
          <el-option v-for="item in division" :label="item.name" :value="item.id" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-table :data="arr" style="width: 96%;margin-left: 2%">
      <el-table-column label="小区照片" width="250">
        <template slot-scope="scope">
          <img :src="scope.row.pic" alt="图片损坏">
        </template>
      </el-table-column>
      <el-table-column label="小区名称" width="180" >
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="辖区" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.divisionName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="经度" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.longitude }}</span>
        </template>
      </el-table-column>
      <el-table-column label="居民楼" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.buildingCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="住户" width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.roomCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="goToPage(scope.row)">定位小区</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.plot.pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="this.plot.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.plot.total">
    </el-pagination>


<!--                                          编辑                                                    -->
    <el-dialog :title=this.title :visible.sync="dialogFormVisible">
      <el-form :model="plots">
        <el-form-item label="小区名称" :label-width="formLabelWidth">
          <el-input v-model="plots.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="小区编号" :label-width="formLabelWidth">
          <el-input v-model="plots.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所辖区域" :label-width="formLabelWidth">
          <el-select v-model="plots.divisionId" placeholder="请选择活动区域">
            <el-option v-for="item in division" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小区照片" :label-width="formLabelWidth">
          <el-upload
            action="/prod-api/base-sixreal/population/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <img :src="plots.pic" alt="">

        </el-form-item>
        <el-form-item label="小区地址" :label-width="formLabelWidth">
          <el-input v-model="plots.address" autocomplete="off"></el-input>
        </el-form-item>





      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="drowMap">绘制定位图</el-button>

      </div>
    </el-dialog>
    <el-dialog title="绘制地图" :visible.sync="ifDrowMap" width="80%">
      <el-form :model="plots">
        <el-col :span="24">
          <el-form-item label="经度" prop="kqLongitude">
            <el-input v-model="plots.longitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="纬度" prop="kqLatitude">
            <el-input v-model="plots.latitude" placeholder="自动带出" clearable :style="{ width: '100%' }" >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="轮廓" prop="kqLatitude">
            <el-input v-model="plots.outline" placeholder="自动带出" clearable :style="{ width: '100%' }" id="outline">
            </el-input>
<!--            <el-input-->
<!--              v-model="outlineDisplay"-->
<!--              placeholder="自动带出，用逗号分隔"-->
<!--              clearable-->
<!--              :style="{ width: '100%' }"-->
<!--              readonly-->
<!--              id="outline"-->
<!--            ></el-input>-->
          </el-form-item>
        </el-col>


        <!-- 控制按钮组 -->
        <div class="map-button" id="container">
          <div ref="gaode_Map1" id="gaode_Map" style="width: 100%; height: 70vh; border: 1px solid #ccc;">
          </div>
          <el-button @click="dialogFormVisible = false" >取 消</el-button>
          <el-button type="primary" @click="update">确 定</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {list, update, add, divisionList, del } from "@/api/community/plot";
import AMapLoader from "@amap/amap-jsapi-loader";
import {map} from "core-js/internals/array-iteration";

window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "a97ace3a685329a45d528a00b082b51d",
};

//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）,
//例如：import 《组件名称》 from '《组件路径》,
  export default {
    //import引入的组件需要注入到对象中才能使用"
    components: {},
    props: {},
    name: "Plot",
    data() {
      //这里存放数据"

    return {
      polygonCoordinates: [],
      ifDrowMap:false,
      drowmap: null,
      drawingManager: null,
      isDrawingEnabled: false, // 控制绘制工具是否“启用”的标记
      arr:[],
      plot:{
        name:'',
        pageNum:1,
        pageSize:5,
        total:1
      },
      isHave: false,
      longitude:'',
      latitude:'',
      dialogFormVisible: false,
      formLabelWidth: '120px',
      plots:{
        longitude: '',
        latitude: '',
        outline: [] // 用于保存点击位置的经纬度信息数组
      },
      outlineDisplay:'',
      aa:1,
      division:[],
      showModal: false,
      map: null,
      auto: null,
      placeSearch: null,
      lnglat: [],
      markers: [],
      position: {},
      tableData:[],
      open: false,
      loading: false,
      // visible: false,
      isDetail: false,
      dataForm: {
        kqName: undefined,
        kqLocation: undefined,
        kqLongitude: undefined,
        kqLatitude: undefined,
        kqWorkUnit: undefined,
        cronkqAccredit: [],
        kqValidCardRange: undefined,
      },
      rules: {},
      input: "",
      input1: "",
      dialogImageUrl: '',
      dialogVisible: false,
      title:'新增小区',
      mouseTool:null,
      uploadedCount: 0, // 用于跟踪上传的图片数量,
    };
  },
  //计算属性 类似于data概念",
  computed: {},
  //监控data中的数据变化",
  watch: {},
  //方法集合",

  methods: {
    cancle(){
      this.plot={
        name:'',
        pageNum:1,
        pageSize:5,
        total:1,
        divisionId:''
      }
      this.list()
    },

    initMap() {
      let centerLen = [116.397452, 39.90918];


      AMapLoader.load({
        key: "085f7d1a48acc9b9611b99096b0a0589",
        version: "2.0",
        plugins: ["AMap.DistrictSearch","AMap.Geocoder","AMap.AutoComplete", "AMap.PlaceSearch",
          'AMap.Scale','AMap.MouseTool']
      })
        .then((AMap) => {
          this.Amap = AMap;

          this.map = new AMap.Map("gaode_Map", {
            viewMode: "3D",
            zoom: 10, // 调整为适合显示整个区域的缩放级别
            center: centerLen,
            resizeEnable: true
          });
          this.map.on("click", this.clickMapHandler);
          // 初始化鼠标绘制工具
          var mouseTool = new AMap.MouseTool(this.map);
          mouseTool.polyline();

            // 监听绘制完成事件

          AMap.event.addListener(mouseTool,
            'draw',
            (e) => {
              if (e.obj.CLASS_NAME === 'AMap.Polyline') {
                // 处理绘制的多边形，可以将其保存或展示到地图上
                var polygon = new AMap.Polygon({
                  path: e.obj.getPath(),
                  strokeColor: "#FF0000",
                  strokeWeight: 2,
                  strokeOpacity: 0.8,
                  fillOpacity: 0.4,
                  fillColor: '#EE2200',
                  zIndex: 50,
                  map: this.map
                });

                // 获取顶点经纬度
                // var path = e.obj.getPath();
                // var vertices = path.map(point => `${point.getLng()},${point.getLat()}`);
                // var verticesStr = vertices.join(';');
                // alert(verticesStr)

                // 关闭绘制工具
                mouseTool.close();

                // 将顶点经纬度赋值给输入框
                // var inputBox = document.getElementById('outline');
                // // this.plots.outline= verticesStr;
                // inputBox.value = verticesStr;
              }
            });

          // 如果需要处理地图点击事件，请确保此事件处理器已正确绑定

        })
        .catch((e) => {
          console.error(e);
        });
    },
    drowMap(){
      this.ifDrowMap=true
      if(this.ifDrowMap){
        this.initMap()
      }

    },



    tenement(plotId){
      // 通过 row.id、row.longitude、row.latitude 来获取对应的值
      const id = plotId;
      this.$router.push({ path: '/community/community/all',  query: {
          id: id
        }})
    },
    handleSuccess(response,file,fileList){
      this.plots.pic=response.data
      this.uploadedCount++; // 更新上传的图片数量
      if (this.uploadedCount === 2) {
        alert("只能选择一张图片，已超出可选图片的数量") // 当上传两张图片时显示弹窗
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },


// 点击地图事件获取经纬度，并添加标记
    // 点击地图事件获取经纬度，并添加标记
    clickMapHandler(e) {
      this.plots.longitude = e.lnglat.getLng();
      this.plots.latitude = e.lnglat.getLat();
       this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.plots.outline.push(this.lnglat);
      // this.setMarker(this.lnglat);
      // 点击地图上的位置，根据经纬度转换成详细地址
      let geocoder = new AMap.Geocoder({});
      let that = this;
      geocoder.getAddress(this.lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          that.dataForm.kqLocation = result.regeocode.formattedAddress;
        } else {
        }
      });
      this.position = {
        longitude: e.lnglat.getLng(),
        latitude: e.lnglat.getLat(),
        address: that.address,
      };

      this.dialogFormVisible=true
      this.input = that.address; //把查询到的地址赋值到输入框
    },
    //  添加标记
    setMarker(lnglat) {
      this.removeMarker();
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },

    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },

    goToPage(row) {
      // 通过 row.id、row.longitude、row.latitude 来获取对应的值
      const id = row.id;
      const longitude = row.longitude;
      const latitude = row.latitude;
      alert(longitude)
      this.$router.push({path: '/map1/index', query: {
          id: id,
          longitude: longitude,
          latitude: latitude
        }})
    },
    look(row) {
      // 通过 row.id、row.longitude、row.latitude 来获取对应的值
      const id = row.id;
      alert(longitude)
      this.$router.push({path: '/community/population', query: {
          id: id
        }})
    },
    handleSizeChange(val) {
      this.plot.pageSize = val
      this.list()
    },
    handleCurrentChange(val) {
      this.plot.pageNum = val
      this.list()
    },
    list() {
      list(this.plot).then(
        res => {
          this.plot.total=res.data.total
          this.arr = res.data.list
        }
      )
    },
    handleEdit(plot) {
      this.title = '修改小区'
      this.aa = 2
      this.plots = plot
      this.dialogFormVisible = true
    },
    update() {
      if (this.aa = 2) {
        update(this.plots).then(
          res => {
            this.$message.success(res.msg)
            this.dialogFormVisible = false
            this.ifDrowMap = false
            this.list()
          }
        )
      }
      if (this.aa = 3) {
        add(this.plots).then(
          res => {
            this.$message.success(res.msg)
            this.dialogFormVisible = false
            this.ifDrowMap = false
            this.list()
          }
        )
      }
      // this.plots.outline.push(",");
    },
    add() {
      this.aa = 3
      // this.plots={}
      this.dialogFormVisible = true
      if (this.dialogFormVisible) {
        this.initMap()

      }

    },
    divisionList() {
      divisionList().then(
        res => {
          this.division = res.data
        }
      )
    },
    handleDelete(plot) {
      del(plot.id).then(
        res => {
          this.$message.success(res.msg)
          this.list()
        }
      )
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）",
  created() {
    this.list()
    this.divisionList()

  },
  //生命周期 - 挂载完成（可以访问DOM元素）",
  mounted() {
  },
  beforeCreate() {
  }, //生命周期 - 创建之前",
  beforeMount() {
  }, //生命周期 - 挂载之前",
  beforeUpdate() {
  }, //生命周期 - 更新之前",
  updated() {
  }, //生命周期 - 更新之后",
  beforeDestroy() {
  }, //生命周期 - 销毁之前",
  destroyed() {
  }, //生命周期 - 销毁完成",
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发",
};
</script>
<style scoped>

</style>
<style>
/* 如果需要，可以添加以下CSS到您的样式表中 */
.card-wrapper {
  /* 可以添加一些额外的样式来控制卡片的间距或布局 */
}

.custom-card .card-header {
  /* 根据需要自定义标题区域的样式 */
  padding: 10px; /* 根据实际情况调整 */
}

.custom-card .card-header .card-title {
  /* 小区名字和地址的容器样式 */
  display: flex;
  flex-direction: column; /* 使名字和地址垂直排列 */
}

.custom-card .card-header .card-image {
  /* 图片的容器样式，这里主要为了演示，实际上图片已经在HTML中直接设置了样式 */
}

.custom-card .card-body {
  /* 详细信息区域的样式 */
  padding: 10px; /* 根据实际情况调整 */

}
</style>
